<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>

    </el-breadcrumb>
    <!-- 卡片视图区域 -->
      <el-card>
        
        <!-- 搜索与添加区 -->



      <el-row :gutter="20">
        <el-col :span = "7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable>

          <el-button slot="append" icon="el-icon-search" @click="getuserslist"></el-button>
          </el-input>
        
        </el-col>
        <el-col :span = "4"> 
          <el-button type = "primary" @click="addDialogVisible =true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- ----------------用户列表区------------------ -->


      <el-table :data="userlist" border stripe>
        <el-table-column type ="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">

            <!-- {{scope.row}} -->

         <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>

        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">


          <el-button type="primary" icon="el-icon-edit" size="mini"
          @click ="editUser(scope.row)"></el-button >
          <!-- 修改 -->


          <el-button type="danger" icon="el-icon-delete" size="mini" @click="opendeluser(scope.row)"></el-button>
          <!-- 删除 -->

          <el-tooltip  effect="dark" content="分配角色" placement="top" :enterable="false">
      
          <el-button type="warning" icon="el-icon-setting" size="mini" @click="setroles(scope.row)"></el-button>
          <!-- 分配角色 -->
            </el-tooltip>
          </template>
        </el-table-column>
         
        
      </el-table>

            <!-- 分页面区 -->


          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
           
        
    </el-card>
              <!-- 添加用户对话框 -->
      <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="70%" @close ="addDialogClose"
      >
      <!-- 内容主体区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" >
      <el-form-item label="用户名" prop="username">
      <el-input v-model="addForm.username"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
      <el-input v-model="addForm.password"></el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
      <el-input v-model="addForm.email"></el-input>
      </el-form-item>


      <el-form-item label="手机" prop="mobile">
      <el-input v-model="addForm.mobile"></el-input>
      </el-form-item>
      </el-form>
      <!-- ---------------------底部区 --------------------->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="validatorUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- -----------------------修改用户----------------- -->
    
    <el-dialog title="修改用户" :visible.sync ="editDialogUser" width="50%" @close = "cleanEidtForm">
      <el-form :model="editUserlist" :rules="addFormRules" ref="editFormRef" label-width="70px" >
        <el-form-item label="用户名">
        <el-input v-model="editUserlist.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="email" prop="email">
        <el-input v-model="editUserlist.email"></el-input>
        </el-form-item>

         <el-form-item label="mobile" prop="mobile">
        <el-input v-model="editUserlist.mobile"></el-input>
        </el-form-item>
        
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogUser = false">取 消</el-button>
        <el-button type="primary" @click="editRevise">确 定</el-button>
      </span>

    </el-dialog>

    <!-- -----------------删除用户对话框 -->

    <el-dialog title="提示" :visible.sync="delFrame"
      width="30%">
      <span>是否要删除 {{deluserid.username}}</span>
      <span slot="footer" class="dialog-footer">
      <el-button @click="delFrame = false">取 消</el-button>
      <el-button type="primary" @click="removeUser">确 定</el-button>
      </span>
    </el-dialog>

        <!-- -----------------分配角色对话框 -->

    <el-dialog title="分配角色" :visible.sync="showsetdialog"
      width="50%" @close="closeSetdialog">
      <div>用户名: {{setRoleInfo.username}}</div>
      <div>权限名称: {{setRoleInfo.role_name}}</div>
      <div>角色名:
        <el-select v-model="selectroleid" placeholder="请选择">
          <el-option v-for="item in roleslist" :value="item.id" :key="item.id" 
           :label="item.roleName" >

          </el-option>
        </el-select>
        </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="showsetdialog = false">取 消</el-button>
      <el-button type="primary" @click="sendRoleId">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  
  data(){

    // 验证邮箱的规则
    var checkEmail = (rule, value, fn) =>{
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if(regEmail.test(value)){
        // 合法
        return fn()
      }

      fn(new Error('邮箱不合法'))
    }
    var checkMobile = (rule, value, fn) =>{
      const regMobile = /^(1[3|5-9])\d{9}$/
      if(regMobile.test(value)){
        // 合法
        return fn()
      }
      fn(new Error('手机不合法'))
    }


    return {
      queryInfo:{
        query:'',
        pagenum:1, //当前页数

        pagesize:5 //每页显示多少条
      },
      userlist:[],
      total:0,
      addDialogVisible:false,
      addForm:{
       //添加用户表单数据 
        username:'',
        password:'',
        email:'',
        mobile:''
      },

      // 修改用户
      editDialogUser:false,
      editUserlist:{},

      // 删除用户窗口
      delFrame:false,
      // 删除用户
      deluserid:{},
      // 分配用户窗体
      showsetdialog:false,

      //选中角色数据
      setRoleInfo:{},
      // 所有角色列表
      roleslist:[],
      // 选中分配用户
      selectroleid:'',
      



      addFormRules:{
        // 对象表单的验证规则
        username:[
          {required :true, message :'请输入用户名',trigger:'blur'},
          { min: 3, max: 10, message:'输入3到10个字符串', trigger:'blur'}
        ],
        password:[
          {required :true, message :'请输入用户密码',trigger:'blur'},
          { min: 6, max: 10, message:'输入6到10个字符串', trigger:'blur'}
        ],
        email:[
          {required :true, message :'请输入email',trigger:'blur'},
          {
            validator:checkEmail,trigger:'blur'
          }
        ],
        mobile:[
          {required :true, message :'请输入mobile',trigger:'blur'},
          {
            validator:checkMobile,trigger:'blur'
          }]

      },

    }
  },
  created(){
    
     this.getuserslist()
    
  },
  methods:{
    //获取用户方法
   async getuserslist(){
     
   const {data:res} = await this.$http.get('users',{ params : this.queryInfo

    
      })
      // console.log(res);
    if(res.meta.status !==200) return this.$message.error('数据获取失败')
 
      this.userlist = res.data.users
      this.total = res.data.total

    },

    //监听 pagesize 改变事件
    handleSizeChange(newSize){          
      this.queryInfo.pagesize = newSize
      this.getuserslist()

    //监听 newPage 改变事件

    },
    handleCurrentChange(newPage){
      this.queryInfo.pagenum = newPage
      this.getuserslist()

      
    },
    //监听 Switch 状态 改变
   async userStateChanged(UserInfo){
      // console.log(UserInfo);
    const {data:res} = await this.$http.put(`users/${UserInfo.id}/state/${
        UserInfo.mg_state}`)
        if(res.meta.status !== 200) {
          UserInfo.mg_state = !UserInfo.mg_state
          return this.$message.error('更新用户状态失败')
        }
        this.$message.success('用户状态更新成功')

    },
    addDialogClose(){
      this.$refs.addFormRef.resetFields()
    },
    validatorUser(){
          // <!-- 添加用户对话框 -->
      this.$refs.addFormRef.validate(async valid => {
        
        if(!valid) return
        // 发起网络请求
      const {data:res} =await this.$http.post('users', this.addForm)
        if(res.meta.status !== 201) { this.$message.error('提交失败')}
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getuserslist()

      })
    },
    // 创建列表清空
    addEditDialog(){
      this.$refs.addFormRef.resetFields()
    },
    // 展示修改用户框
    showEditUser(){     
      this.editDialogUser = true
    },
    // Edit用户列表获取
   async editUser(user){
      this.editDialogUser = true
      
     const {data:res} = await this.$http.get('users/' + user.id)
     if(res.meta.status !== 200){
       return this.$message.error('获取失败')
     }
     this.editUserlist = res.data
     this.getuserslist()
  
    },
    // 清空edit user 
    cleanEidtForm(){
      this.$refs.editFormRef.resetFields()
    },
    // 表单预验证,修改
    editRevise(){
      this.$refs.editFormRef.validate(async vali =>{
        if(!vali)
        {return this.$message.error('修改失败')
        }

        const {data:res} = await this.$http.put('users/' + this.editUserlist.id,{email:this.editUserlist.email,
        mobile:this.editUserlist.mobile})
        if(res.meta.status !== 200){
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.getuserslist()
        this.editDialogUser = false
        }
      )
    },
// 打开删除用户对话框
    opendeluser(id){
      this.deluserid = id
      this.delFrame = true
    },
    // 删除用户
   async removeUser(){
    const {data:res} = await this.$http.delete('users/' + this.deluserid.id)
    if(res.meta.status !== 200){
      return this.$message.error('请求删除失败')
    }
    this.$message.success('删除成功')
    this.getuserslist()
    this.delFrame = false
    },
    // 分配角色
    async setroles(id){
      // 获取角色列表
      this.setRoleInfo = id
    const {data:res} = await this.$http.get('roles')
    if(res.meta.status !== 200) {
      return this.$message.error('获取角色列表失败')
    }
    this.roleslist = res.data
    this.showsetdialog = true
     
    },
    // 发送分配角色
    async sendRoleId(){
      if(!this.selectroleid){
        return this.$message.error('不能为空')
      }
    const {data:res} = await this.$http.put(`users/${this.setRoleInfo.id}/role`,{
      rid:this.selectroleid})
    if(res.meta.status !== 200){
      return this.$message.error('获取出错')
    }this.$message.success('修改成功')
    this.getuserslist()
    this.showsetdialog = false
    },
    closeSetdialog(){
      this.selectroleid = ''
      this.setRoleInfo = {}
    }
  },
  
}
</script>

<style lang ="less" scoped>

</style>